var { Client, Message } = require('../../utils/paho-mqtt.js')

const app = getApp()
//console.log(wx.getUserInfo())







// camera.js
Page({
  data: {
    index: 0,
    //array: ['黑AVC815', '黑A234111', '黑A88888'],
    array: [],//车辆下拉框
    cheLiangs: [],
    kongZhiArr: [],//当前页面控制
    kongZhiArrs: [],//所有控制
    dept_id_current: 100,//当前的页面控制的父id,默认0顶级
    ifHiddenBack: true,
    statusBackground: '#a9a9a9',//77a900 状态圆圈的颜色
    deviceId: "",
    name: "",
    serviceId: "",
    characteristicId: "",
    chs: [],
    imageDianJiCss: [],//图片（控制命令）点击时候的css
    imageCurrentTarget: {}//图片当前点击的对象
    //"width: 30%;margin-right:2%;margin-top:1%"
  },
  onLoad: function (option) {



    let that = this;

    try {
      //app.globalData.client.disconnect()
    }
    catch (e) {
      console.log(e)
    }

    //状态灯
    that.setData({
      statusBackground: '#a9a9a9'
    })


    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: app.globalData.urlGlobal + '/commonZwl/huoquOpenid', //url
            data: {
              code: res.code
            },
            success: function (res) {
              console.log(res)
              //let openid=res.data.openid;
              //console.log(openid)

              var obj = {}
              //obj.openid='o0wKt5WHIexcRMhc96I72XWxLdNk'
              obj.openid = res.data.openid;
              wx.setStorageSync('user', obj)

              that.initCheLiang()

            },
            fail: function (e) {
              console.log(e)
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },

  




  subscribe: function (filter, subscribeOptions) {
    let that = this
    // 订阅
    var client = app.globalData.client
    if (client && client.isConnected()) {
      wx.showToast({
        title: '服务器连接成功'
      })
      return client.subscribe(filter, subscribeOptions);
    } else {
      app.globalData.mqttConnetc(app.globalData);
      //that.doConnect()
    }
    // wx.showToast({
    //   title: '订阅失败',
    //   icon: 'success',
    //   duration: 2000
    // })
  },
  publish: function (topic, message, qos = 0, retained = false) {
    let that = this;
    // 发布
    var client = app.globalData.client
    if (client && client.isConnected()) {
      var message = new Message(message);
      message.destinationName = topic;
      message.qos = qos;
      message.retained = retained;
      // wx.showToast({
      //   title: '发布成功'
      // })
      return client.send(message);
    }
    else {
      that.doConnect()
    }
    wx.showToast({
      title: '发送失败',
      icon: 'success',
      duration: 2000
    })
  },
  setOnMessageArrived: function (onMessageArrived) {
    if (typeof onMessageArrived === 'function') {
      this.data.onMessageArrived = onMessageArrived
    }
  },
  setOnConnectionLost: function (onConnectionLost) {
    if (typeof onConnectionLost === 'function') {
      this.data.onConnectionLost = onConnectionLost
    }
  },
  doSubscribe: function (subTopic) {

    this.subscribe(subTopic, {
      qos: 1
    })
  },
  doPublish: function (pubTopic, msg) {
    this.publish(pubTopic, msg, 1, false)
  },
  doConnect: function () {
    var that = this;
    // if (that.data.client && that.data.client.isConnected()) {
    //   wx.showToast({
    //     title: '不要重复连接'
    //   })
    //   return
    // }
    // var client = new Client("wss://www.zcxbb.com/mqtt", that.randomString());
    let client = app.globalData.client
    try {


      client.onMessageArrived = function (msg) {
        console.log(msg)
        str=msg.payloadString
        if (str === "QQQQ") {
          this.setData({
            statusBackground: '#77a900'
          })
        }

        if (typeof that.data.onMessageArrived === 'function') {
          return that.data.onMessageArrived(msg)
        }

        // wx.showModal({
        //   title: msg.destinationName,
        //   content: msg.payloadString
        // })
      }

      client.onConnectionLost = function (responseObject) {
        if (typeof that.data.onConnectionLost === 'function') {
          return that.data.onConnectionLost(responseObject)
        }
        if (responseObject.errorCode !== 0) {
          console.log("onConnectionLost:" + responseObject.errorMessage);
          if (responseObject.errorCode === 8) {
            that.doConnect()
          }
        }
      }


      let subTopic = that.data.deviceId.replace(/:/g, "")
      that.doSubscribe(subTopic)


    }
    catch (e) {
      console.log(e)
    }

  },





  kongZhiArrGetChild(dept_id) {
    let rtn = []
    let data = this.data.kongZhiArrs;
    for (let i = 0; i < data.length; i++) {
      let obj = data[i]
      if (obj.parent_id === dept_id) {
        rtn.push(obj);
      }
    }
    return rtn
  },

  kongZhiArrGetSelf(dept_id) {
    let rtn = {}
    let data = this.data.kongZhiArrs;
    for (let i = 0; i < data.length; i++) {
      let obj = data[i]
      if (obj.dept_id === dept_id) {
        rtn = obj;
      }
    }
    return rtn
  },

  ifHasChildKongZhi(arrKongZhi) {
    let rtn = true;
    for (let i = 0; i < arrKongZhi.length; i++) {
      let obj = data[i]
      if (obj.dept_id === dept_id) {
        rtn = obj;
      }
    }
    return rtn
  },

  //初始化已绑定车辆
  initCheLiang(chePaiHao) {



    let that = this

    // let c=that.data.client
    //
    // if(c!=null){
    //   
    //   c.disconnect()
    // }

    let sql = "select * from qi_che_she_bei where openid='" + wx.getStorageSync('user').openid + "'"
    wx.request({
      url: app.globalData.urlGlobal + '/commonZwl/getZwl', //url
      method: 'GET', //请求方式
      header: {
        'Content-Type': 'application/json',
      },
      data: {
        sql: sql,  //参数
      },
      success: function (res) {
        console.log("initCheLiang:" + JSON.stringify(res))

        let data = res.data.rtn;
        let a = []

        for (let i = 0; i < data.length; i++) {
          a.push(data[i].ming_cheng)
        }
        that.setData({
          array: a
        })
        that.setData({
          cheLiangs: data
        })

        if (a.length > 0) {

          that.initKongZhi(a[0], data[0].device_id)
        }




      },
      fail: function () {
        console.log("请求数据失败");
      },
      complete: function () {
        // complete
      }
    })
  },

  initKongZhi(chePaiHao, deviceId) {
    let that = this

    this.setData({
      deviceId: deviceId
    })



    // let sql="select * from qi_che_kong_zhi where dept_id in"+
    // " (select dept_id from qi_che_che_liang_kong_zhi "+
    // " where role_id=(select role_id from qi_che_che_liang where role_name='"+chePaiHao+"'))"+
    // " and del_flag = 0"+
    // " order by order_num";

    let sql = "select * from qi_che_kong_zhi where dept_id in\n" +
      "     (select dept_id from qi_che_che_liang_kong_zhi \n" +
      "     where role_id=(select role_id from qi_che_che_liang where role_id in (select qi_che_che_liang_id from qi_che_she_bei WHERE device_id='" + deviceId + "')))\n" +
      "     and del_flag = 0\n" +
      "    order by order_num"

    wx.request({
      url: app.globalData.urlGlobal + '/commonZwl/getZwl', //url
      method: 'GET', //请求方式
      header: {
        'Content-Type': 'application/json',
      },
      data: {
        sql: sql,  //参数
      },
      success: function (res) {
        let data = res.data.rtn;
        let a = []
        for (let i = 0; i < data.length; i++) {
          let obj = data[i]
          obj.tuBiaoLuJing = app.globalData.urlGlobal + obj.tuBiaoLuJing
          obj.tuBiaoDianJiLuJing = app.globalData.urlGlobal + obj.tuBiaoDianJiLuJing
          if (obj.parent_id == 100) {
            a.push(obj)
          }
        }
        console.log(data)


        for (let i = 0; i < a.length; i = i + 3) {
          console.log(i)
        }

        that.setData({
          kongZhiArr: a,
          kongZhiArrs: data
        })
        var cssArrTemp = [];
        for (var i = 0; i < that.data.kongZhiArr.length; i++) {
          cssArrTemp.push("width: 30%;margin-right:2%;margin-top:1%")
        }
        that.setData({
          imageDianJiCss: cssArrTemp
        })

        that.doConnect()

        setTimeout(function () {
          that.openBluetoothAdapter()
        }, 1000)




      },
      fail: function () {
        console.log("请求数据失败");
      },
      complete: function () {
        // complete 
      }
    })
  },

  /*
  *图片按下
  * */
  imageAnXia(e) {
    this.setData({
      imageCurrentTarget: e.currentTarget
    })
    let id = e.currentTarget.id

    let tmpArr=this.data.kongZhiArr

    if(tmpArr[id].qi_che_liang_tai=="1"){//qi_che_liang_tai 命令图标是否是两态 0否 1是
      let tmp1=tmpArr[id].tuBiaoLuJing
      tmpArr[id].tuBiaoLuJing=tmpArr[id].tuBiaoDianJiLuJing
      tmpArr[id].tuBiaoDianJiLuJing=tmp1
      this.setData({
        kongZhiArr:tmpArr
      })
    }else{
      this.data.imageDianJiCss[id] = "width: 30%;margin-right:2%;margin-top:1%;transform: scale(0.7)"
      this.setData({
        imageDianJiCss: this.data.imageDianJiCss
      })
    }

    //console.log("this.data.imageDianJiCss:"+this.data.imageDianJiCss)


    let that = this;


    let dept_id = e.currentTarget.dataset.command.dept_id
    let kongZhi1 = e.currentTarget.dataset.command

    let kongZhi = this.kongZhiArrGetChild(dept_id)
    if (kongZhi.length > 0) {
      that.setData({
        dept_id_current: dept_id,
        kongZhiArr: kongZhi,
        ifHiddenBack: false
      })

      var cssArrTemp = [];
      for (var i = 0; i < that.data.kongZhiArr.length; i++) {
        cssArrTemp.push("width: 30%;margin-right:2%;margin-top:1%")
      }
      that.setData({
        imageDianJiCss: cssArrTemp
      })

    }
    if (kongZhi1.leader) {//kongZhi1.leader自定义的命令
      if (kongZhi1.leader != "") {
        console.log(kongZhi1.leader)
        if (kongZhi1.leader.split(",").length > 1) {//按下一个命令，抬起一个命令，这里是按下命令
          that.writeBLECharacteristicValue(kongZhi1.leader.split(",")[0])
          let topic = that.data.deviceId.replace(/:/g, "")
          that.doPublish(topic, kongZhi1.leader.split(",")[0] + "\n")
          console.log("多命令按下" + kongZhi1.leader.split(",")[0])
        }
      }
    }
  },
  imageTaiQi(e) {
    // let id=e.currentTarget.id
    // this.data.imageDianJiCss[id]="width: 30%;margin-right:2%;margin-top:1%;transform: scale(1)"
    // this.setData({
    //   imageDianJiCss:this.data.imageDianJiCss
    // })
    this.imageDianJi(e)
  },

  mqttSend(e){
    this.writeBLECharacteristicValue("")
    // wx.navigateTo({
    //   url: '/pages/bang_ding/bang_ding',
    // })
  },
  /*
  *图片抬起
  * */
  imageDianJi(e) {
    let that = this

    let imageCurrentTarget = this.data.imageCurrentTarget
    if (imageCurrentTarget.id) {//判断某个图片是否被按下
      //let id = e.currentTarget.id
      let id = imageCurrentTarget.id

      this.data.imageDianJiCss[id] = "width: 30%;margin-right:2%;margin-top:1%;transform: scale(1)"
      this.setData({
        imageDianJiCss: this.data.imageDianJiCss
      })





      // let dept_id = e.currentTarget.dataset.command.dept_id
      // let kongZhi1 = e.currentTarget.dataset.command

      let dept_id = imageCurrentTarget.dataset.command.dept_id
      let kongZhi1 = imageCurrentTarget.dataset.command

      let kongZhi = this.kongZhiArrGetChild(dept_id)
      if (kongZhi.length > 0) {
        that.setData({
          dept_id_current: dept_id,
          kongZhiArr: kongZhi,
          ifHiddenBack: false
        })

        var cssArrTemp = [];
        for (var i = 0; i < that.data.kongZhiArr.length; i++) {
          cssArrTemp.push("width: 30%;margin-right:2%;margin-top:1%")
        }
        that.setData({
          imageDianJiCss: cssArrTemp
        })

      }
      if (kongZhi1.leader) {//kongZhi1.leader自定义的命令
        if (kongZhi1.leader != "") {
          console.log(kongZhi1.leader)
          if (kongZhi1.leader.split(",").length > 1) {//按下一个命令，抬起一个命令，这里要抬起命令
            that.writeBLECharacteristicValue(kongZhi1.leader.split(",")[1])
            let topic = that.data.deviceId.replace(/:/g, "")
            that.doPublish(topic, kongZhi1.leader.split(",")[1] + "\n")
            console.log("多命令抬起" + kongZhi1.leader.split(",")[1])
          } else {
            console.log("单命令")
            that.writeBLECharacteristicValue(kongZhi1.leader)
            let topic = that.data.deviceId.replace(/:/g, "")
            that.doPublish(topic, kongZhi1.leader + "\n")
          }
        }
      }
      that.setData({
        imageCurrentTarget: {}//清空图片点击事件
      })
    }



    /*
    let that=this;
    console.log(e)
    let arr=[]
    let id=e.target.id
    arr[id]="imageDianJi"
    this.setData({
      imageClassArr:arr
    })
    let s=setInterval(() => {
      arr[id]=""
      that.setData({
      imageClassArr:arr
    })
    clearInterval(s)
    }, 100);
    */
  },
  back() {//返回
    let that = this;

    let parent_id = this.kongZhiArrGetSelf(this.data.dept_id_current).parent_id
    let kongZhi = this.kongZhiArrGetChild(parent_id)

    var cssArrTemp = [];
    for (var i = 0; i < kongZhi.length; i++) {
      cssArrTemp.push("width: 30%;margin-right:2%;margin-top:1%")
    }
    that.setData({
      imageDianJiCss: cssArrTemp
    })


    if (parent_id === 100) {
      that.setData({
        dept_id_current: parent_id,
        kongZhiArr: kongZhi,
        ifHiddenBack: true
      })
    } else {
      that.setData({
        dept_id_current: parent_id,
        kongZhiArr: kongZhi,
      })
    }
  },

  bindPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })

    this.initKongZhi(this.data.array[e.detail.value], this.data.cheLiangs[e.detail.value].device_id)
  },

  sao_ma() {
    wx.scanCode({
      success: (res) => {
        console.log(res)

        if (res.result) {
          if (res.result.length == 12) {
            //let deviceIdSaoMao="84CCA857CDC6";
            let deviceIdSaoMao = res.result;
            let deviceId = ""
            for (let i = 0; i < 6; i++) {
              let s = deviceIdSaoMao.substring(i * 2, i * 2 + 2)
              if (i != 5) {
                deviceId += s + ":"
              } else {
                deviceId += s
              }
            }
            wx.navigateTo({
              url: '/pages/bang_ding/bang_ding?deviceId=' + deviceId,
            })
          } else {
            wx.showToast({
              title: '错误二维码！',
            })
          }
        }





      }
    })
  },
  error(e) {
    console.log(e.detail)
  },


  openBluetoothAdapter() {
    let that = this;
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        //this.startBluetoothDevicesDiscovery()
        this.createBLEConnection();
        this.setData({
          connected: true
        })
      },
      fail: (res) => {
        console.log(JSON.stringify(res))

        wx.showToast({
          title: "请开启蓝牙",
        })

        this.setData({
          connected: false
        })
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            //console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              //this.createBLEConnection();
            }
          })
        }
      }
    })
  },


  createBLEConnection() {

    let that = this;


    const deviceId = this.data.deviceId
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        that.setData({
          connected: true,
        })
        this.getBLEDeviceServices(deviceId)
      },
      complete: (res) => {
        console.log("createBLEConnection complete:" + res)
        if (res.errCode === -1) {
          that.setData({
            connected: true,
          })
          this.getBLEDeviceServices(deviceId)
        }
      },
    })
  },

  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },

  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })

            this.setData({
              deviceId: deviceId,
              serviceId: serviceId,
              characteristicId: item.uuid
            })



            //this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {

      let str = bufferToString(characteristic.value)
      var that = this;
      if (str === "WWWW") {
        this.setData({
          statusBackground: '#77a900'
        })
      }

      /*
      wx.showModal({
        title:str,
        showCancel:false
      })
      */

      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }

      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
      console.log(data)
      //this.showModal(JSON.stringify(data))
    })
  },

  writeBLECharacteristicValue(value) {

    if (!this.data.connected) {
      wx.showToast({
        title: '蓝牙连接中',
      })
    }

    //蓝牙命令编辑
    //value="~!AABW"+value+"\n"
    //value="~!BB"+value+"\n"
    value = value + "\n"

    for (let i = 0; i < value.length; i = i + 10) {
      let s = value.substring(i, i + 10)
      this.writeBlue(s)
    }

  },
  writeBlue(val) {
    let that = this;
    let command = val;
    var buf = new ArrayBuffer(command.length); //
    var bufView = new Uint8Array(buf);
    for (var i = 0, strLen = command.length; i < strLen; i++) {
      bufView[i] = command.charCodeAt(i);
    }
    let str = bufferToString(buf)
    console.log(str)
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicId,
      value: buf,
      /*
      success:(res)=>{
        wx.showModal({
          title:JSON.stringify(res),
          showCancel:false
        })
      }
       */
    })


    //this.openBluetoothAdapter();
    //var command=event.currentTarget.dataset.command


    /*
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    */

    //字符串转为ArrayBuffer对象，参数为字符串
    //var str=this.input_fa_song_value;
    //console.log(str);


  }

})

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function bufferToString(buffer) {
  return String.fromCharCode.apply(null, new Uint8Array(buffer))
}